package com.atguigu.yygh.order.service.impl;

import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.order.mapper.RefundInfoMapper;
import com.atguigu.yygh.order.service.RefundInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 杨林
 * @create 2022-11-19 11:40 星期六
 * description:
 */
@Service
public class RefundInfoServiceImpl extends ServiceImpl<RefundInfoMapper,RefundInfo> implements RefundInfoService {


    /**
     * 根据支付记录创建退款记录
     * @param paymentInfo
     * @return
     */
    @Override
    public RefundInfo saveRefundInfo(PaymentInfo paymentInfo) {

        //查询退款订单是否存在
        QueryWrapper<RefundInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", paymentInfo.getOrderId());
        queryWrapper.eq("payment_type", paymentInfo.getPaymentType());
        RefundInfo existRefundInfo = baseMapper.selectOne(queryWrapper);
        if (existRefundInfo != null){
            return existRefundInfo;
        }

        //创建退款记录
        RefundInfo refundInfo = new RefundInfo();

        refundInfo.setOrderId(paymentInfo.getOrderId());
        refundInfo.setOutTradeNo(paymentInfo.getOutTradeNo());
        refundInfo.setPaymentType(paymentInfo.getPaymentType());
        refundInfo.setTotalAmount(paymentInfo.getTotalAmount());
        //refundInfo.setTradeNo(paymentInfo.getTradeNo());
        refundInfo.setSubject(paymentInfo.getSubject());
        refundInfo.setRefundStatus(RefundStatusEnum.UNREFUND.getStatus());  //1:退款中
        refundInfo.setCreateTime(new Date());

        //添加到数据库
        baseMapper.insert(refundInfo);

        return refundInfo;
    }
}
